using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Custom.Tools.Curve;
namespace Custom.Tools.WayLineDemo
{
    public class WayLine : MonoBehaviour
    {
        public int amountRatio = 1;

        public CatmullRom cRom = new();

        [SerializeField]
        private List<Transform> nodes = new();
        private void Awake()
        {
            FindNodes();
            cRom.SplitWayPoints(GetWayPoints(), amountRatio);
            Debug.Log("总距离" + cRom.TotalDistance);
        }

        private void FindNodes()
        {
            if (nodes == null)
            {
                nodes = new();
                int length = transform.childCount;
                for (int i = 0; i < length; i++)
                {
                    nodes.Add(transform.GetChild(i));
                }
            }

        }

        private Vector3[] GetWayPoints()
        {
            Vector3[] wayPoints = new Vector3[nodes.Count];

            for (int i = 0; i < nodes.Count; i++)
            {
                var pos = nodes[i].position;

                if (Application.isPlaying)
                {

                    pos.y = 0;
                }

                wayPoints[i] = pos;
            }

            return wayPoints;
        }

        // Start is called before the first frame update。
        void Start()
        {

        }

        // Update is called once per frame
        void Update()
        {

        }

        private void OnDrawGizmos()
        {
            DrawGizmos(false);
        }


        private void OnDrawGizmosSelected()
        {
            DrawGizmos(true);
        }

        private void DrawGizmos(bool selected)
        {
            var Segments = cRom.SplitWayPoints(GetWayPoints(), amountRatio);

            if (nodes.Count > 1)
            {
                Gizmos.color = selected ? Color.yellow : Color.red;

                for (int n = 0; n < nodes.Count; ++n)
                {
                    if (nodes[n].transform != this.transform)
                        Gizmos.DrawWireSphere(nodes[n].position, .1f);
                }


                Vector3 prev = cRom.StartPoint;
                for (int i = 0; i < Segments.Count; i++)
                {
                    var segment = Segments[i];
                    var ways = segment.nodes;
                    for (int j = 0; j < segment.nodes.Count; j++)
                    {
                        Vector3 next = ways[j].point;
                        Gizmos.DrawLine(prev, next);
                        prev = next;
                    }
                }

            }

        }
    }
}

